package pkg

import (
	"fmt"
	"math/rand"
	"time"
)

type TokenQ struct {
	Tokens chan int
}

func (T *TokenQ) Get(gosum int, f func(i int)) (tokenValue int) {
	//自返还
	tokenValue = <-T.Tokens
	defer T.TokenBreak(tokenValue)

	//处理业务
	f(gosum)
	time.Sleep(time.Duration(rand.Int63n(1000) * int64(time.Microsecond)))
	return tokenValue
}

//主动返还
func (T *TokenQ) TokenBreak(tokenValue int) {
	T.Tokens <- tokenValue
	return
}
func main() {
	N := 100
	TokenChannel := make(chan int, N)
	for i := 0; i < N; i++ {
		TokenChannel <- i
	}
	T := TokenQ{Tokens: TokenChannel}

	for i := 0; i < 1000; i++ {
		go func(i int) {
			tokenVlaue := T.Get(i, func(i int) {
				fmt.Printf("do smothing %d \n", i)
			})
			fmt.Printf("go %d get token %d \n", i, tokenVlaue)
		}(i)

	}

	time.Sleep(1 * time.Second)
	//fmt.Printf("get Token %d \n",tokenVlaue)
	return
}
